#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

QString SERVER_IP = "127.0.0.1";
quint16 SERVER_PORT = 8080;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("cf client");

    socket = new QTcpSocket(this);
    //非阻塞链接
    socket->connectToHost(SERVER_IP,SERVER_PORT);
    //等待链接建立，确认是否成功
    bool ret = socket->waitForConnected();
    if(!ret)
    {
        QMessageBox::critical(this,"链接服务器出错",socket->errorString());
        exit(1);
    }
    connect(socket,&QTcpSocket::readyRead,this,[=](){
        QString response = socket->readAll();
        ui->listWidget->addItem("服务器: " + response);
    });
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    const QString& text = ui->lineEdit->text();

    socket->write(text.toUtf8());

    ui->listWidget->addItem("客户端: " + text);

    ui->lineEdit->setText("");
}
